// ==UserScript==
// @name         URL重定向器-移动端
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  自定义URL重定向规则，支持导入导出和URL Pattern
// @author       Cursor
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_addStyle
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';
    
    // 简单的URL Pattern实现（如果浏览器不支持）
    if (typeof URLPattern === 'undefined') {
        window.URLPattern = class URLPattern {
            constructor(pattern) {
                this.pattern = pattern;
                
                // 解析pattern字符串
                this.regex = this._parsePattern(pattern);
                this.groupNames = this._extractGroupNames(pattern);
            }
            
            _parsePattern(pattern) {
                // 将:param转换为命名捕获组
                let regexStr = pattern.replace(/\/:[^\/]+/g, (match) => {
                    const paramName = match.substring(2);
                    return `/(?<${paramName}>[^/]+)`;
                });
                
                // 处理URL的特殊字符
                regexStr = regexStr.replace(/([.?+^$[\]\\(){}|-])/g, "\\$1");
                
                return new RegExp(`^${regexStr}$`);
            }
            
            _extractGroupNames(pattern) {
                const groupNames = [];
                const matches = pattern.match(/\/:[^\/]+/g) || [];
                matches.forEach(match => {
                    groupNames.push(match.substring(2));
                });
                return groupNames;
            }
            
            test(url) {
                return this.regex.test(url);
            }
            
            exec(url) {
                const match = this.regex.exec(url);
                if (!match) return null;
                
                // 构造返回值，模拟URLPattern.exec()的返回格式
                return {
                    pathname: {
                        groups: match.groups || {}
                    }
                };
            }
        };
    }
    
    // 添加样式
    GM_addStyle(`
        #redirector-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 600px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            font-family: "Microsoft YaHei", Arial, sans-serif;
            z-index: 9999;
            padding: 15px;
            display: none;
            max-height: 90vh;
            overflow-y: auto;
        }
        #redirector-header {
            display: flex !important;
            justify-content: space-between !important;
            align-items: center !important;
            width: 100% !important;
            position: relative !important;
            margin-bottom: 15px !important;
            border-bottom: 1px solid #eee !important;
            padding-bottom: 10px !important;
        }
        #redirector-header h2 {
            margin: 0;
            font-size: 18px;
            color: #333;
        }
        .header-actions {
            display: flex;
            gap: 8px;
        }
        .theme-toggle {
            cursor: pointer;
            font-size: 18px;
            background: none;
            border: none;
            padding: 0;
        }
        .section-title {
            font-size: 16px;
            margin: 15px 0 10px 0;
            color: #444;
            font-weight: bold;
        }
        .input-group {
            width: 100% !important;
            display: flex !important;
            flex-direction: column !important;
            margin-bottom: 15px !important;
        }
        .input-row {
            display: flex;
            gap: 8px;
            align-items: center;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }
        .arrow {
            color: #888;
            font-size: 18px;
            flex-shrink: 0;
        }
        select, input[type="text"], textarea {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            flex: 1;
            font-family: "Microsoft YaHei", Arial, sans-serif;
            font-size: 14px;
            min-height: 44px;
            box-sizing: border-box;
        }
        
        /* 特殊处理select元素 */
        select {
            padding-right: 30px; /* 增加右侧空间避免被截断 */
            background-color: white; /* 确保背景色正确 */
            min-height: 44px;
        }
        
        textarea {
            min-height: 150px;
            height: auto;
            width: 100%;
            resize: vertical;
        }
        button {
            padding: 10px 14px;
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            font-family: "Microsoft YaHei", Arial, sans-serif;
            font-size: 14px;
            transition: all 0.2s;
            min-height: 44px;
            min-width: 60px;
            touch-action: manipulation;
        }
        button:hover {
            background-color: #e5e5e5;
        }
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        #add-rule {
            background-color: #4a90e2;
            color: white;
            border-color: #3a80d2;
        }
        #add-rule:hover {
            background-color: #3a80d2;
        }
        .redirector-rules {
            margin-top: 15px;
            max-height: 350px;
            overflow-y: auto;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 8px;
        }
        .rule-item {
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
            display: flex;
            flex-direction: column;
            background-color: #f9f9f9;
        }
        .rule-item-content {
            flex: 1;
            overflow: hidden;
            padding-right: 10px;
            margin-bottom: 10px;
        }
        .rule-item-content div {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 3px;
        }
        .rule-actions {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
            justify-content: flex-end;
        }
        .dark-mode {
            background-color: #333;
            color: #fff;
        }
        .dark-mode #redirector-header {
            border-color: #555 !important;
        }
        .dark-mode select, .dark-mode input[type="text"], .dark-mode textarea {
            background-color: #444;
            color: #fff;
            border-color: #555;
        }
        .dark-mode button {
            background-color: #555;
            color: #fff;
            border-color: #666;
        }
        .dark-mode button:hover {
            background-color: #666;
        }
        .dark-mode #add-rule {
            background-color: #4a90e2;
            border-color: #3a80d2;
        }
        .dark-mode #add-rule:hover {
            background-color: #3a80d2;
        }
        .dark-mode .rule-item, .dark-mode .redirector-rules {
            border-color: #555;
            background-color: #444;
        }
        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 15px;
            flex-wrap: wrap;
        }
        .import-export-container {
            margin-top: 15px;
            display: none;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
        }
        .import-export-tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #eee;
            overflow-x: auto;
            white-space: nowrap;
        }
        .import-export-tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 14px;
        }
        .import-export-tab.active {
            border-bottom-color: #4a90e2;
            color: #4a90e2;
            font-weight: bold;
        }
        .import-export-content {
            display: none;
            margin-bottom: 20px;
        }
        .import-export-content.active {
            display: block;
        }
        .file-drop-area {
            border: 2px dashed #ccc;
            border-radius: 5px;
            padding: 30px;
            text-align: center;
            margin-bottom: 15px;
            cursor: pointer;
            transition: background 0.3s, border-color 0.3s;
        }
        .file-drop-area:hover,
        .file-drop-area.active {
            background: rgba(74, 144, 226, 0.1);
            border-color: #4a90e2;
        }
        .dark-mode .file-drop-area {
            border-color: #555;
        }
        .dark-mode .file-drop-area:hover,
        .dark-mode .file-drop-area.active {
            background: rgba(74, 144, 226, 0.2);
            border-color: #4a90e2;
        }
        .file-input-btn {
            display: inline-block;
            padding: 8px 15px;
            background: #4a90e2;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            transition: background 0.3s;
        }
        .file-input-btn:hover {
            background: #3a80d2;
        }
        .file-name {
            margin-top: 10px;
            font-size: 14px;
            word-break: break-all;
            color: #4a90e2;
        }
        .file-msg {
            color: #888;
        }
        .dark-mode .file-msg {
            color: #aaa;
        }
        .dark-mode .import-export-tabs {
            border-color: #555;
        }
        .dark-mode .import-export-container {
            border-color: #555;
        }
        .close-button {
            position: absolute;
            top: 10px;
            right: 10px;
            cursor: pointer;
            font-size: 18px;
            background: none;
            border: none;
            color: #888;
        }
        .tabs {
            display: flex !important;
            flex-wrap: nowrap !important;
            overflow-x: auto !important;
            scrollbar-width: thin !important;
            margin-bottom: 15px !important;
            border-bottom: 1px solid #eee !important;
            gap: 5px !important;
        }
        .tab {
            padding: 10px 15px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 15px;
            white-space: nowrap;
            flex-shrink: 0;
        }
        .tab.active {
            border-bottom-color: #4a90e2;
            color: #4a90e2;
            font-weight: bold;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .dark-mode .tabs {
            border-color: #555 !important;
        }
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9998;
            display: none;
        }
        .toggle-rule, .delete-rule, .edit-rule {
            padding: 8px 12px;
            min-height: 42px;
        }
        .edit-rule {
            background-color: #ff9800;
            color: white;
            border-color: #f57c00;
        }
        .edit-rule:hover {
            background-color: #f57c00;
        }
        .toggle-rule[data-enabled="true"] {
            background-color: #4caf50;
            color: white;
            border-color: #43a047;
        }
        .toggle-rule[data-enabled="false"] {
            background-color: #f44336;
            color: white;
            border-color: #e53935;
        }
        #test-result {
            margin-top: 8px;
            font-size: 14px;
            padding: 5px;
        }
        #close-import-export {
            margin-top: 20px;
            padding: 8px 30px;
            background-color: #f44336;
            color: white;
            border-color: #e53935;
        }
        #close-import-export:hover {
            background-color: #e53935;
        }
        .dark-mode #close-import-export {
            background-color: #f44336;
            border-color: #e53935;
        }
        .dark-mode #close-import-export:hover {
            background-color: #d32f2f;
        }
        /* 按钮样式增强 */
        #import-rules-text, #export-rules-text, #import-rules-file, #export-rules-file {
            min-width: 100px;
            padding: 10px 15px;
            font-size: 14px;
        }
        
        /* 导入导出容器内部间距增加 */
        .import-export-content {
            padding: 10px;
        }
        
        /* 暗黑模式导入导出增强 */
        .dark-mode .import-export-content {
            background-color: #3a3a3a;
            border-radius: 4px;
        }
        
        /* 导入导出按钮增强 */
        #import-rules-text, #export-rules-text {
            background-color: #4a90e2;
            color: white;
            border-color: #3a80d2;
        }
        #import-rules-text:hover, #export-rules-text:hover {
            background-color: #3a80d2;
        }
        #import-rules-file, #export-rules-file {
            background-color: #4a90e2;
            color: white;
            border-color: #3a80d2;
        }
        #import-rules-file:hover, #export-rules-file:hover {
            background-color: #3a80d2;
        }
        #import-rules-file:disabled {
            background-color: #9e9e9e;
            border-color: #757575;
        }
        /* 强制修复下拉菜单问题 */
        select#rule-type {
            appearance: menulist !important;
            -webkit-appearance: menulist !important;
            -moz-appearance: menulist !important;
            background-image: none !important;
            padding-right: 25px !important;
            width: 130px !important;
            min-width: 130px !important;
            text-overflow: ellipsis !important;
            background-color: transparent !important;
            z-index: 100 !important;
            position: relative !important;
            height: 44px !important;
            flex: 0 0 auto !important; /* 防止被挤压 */
            font-size: 14px !important;
            line-height: 1.4 !important;
        }
        
        /* 防止下拉菜单被遮挡 */
        select#rule-type option {
            background-color: white !important;
            color: black !important;
            padding: 8px !important;
            font-size: 14px !important;
            line-height: 1.4 !important;
        }
        
        .dark-mode select#rule-type option {
            background-color: #444 !important;
            color: white !important;
        }
        
        /* 移动端特定样式 */
        @media (max-width: 600px) {
            #redirector-container {
                width: 95%;
                padding: 12px;
                max-height: 85vh;
            }
            
            #redirector-header h2 {
                font-size: 16px;
            }
            
            .input-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .input-row input[type="text"] {
                width: 100%;
            }
            
            .arrow {
                align-self: flex-start;
                margin: 5px 0;
            }
            
            select#rule-type {
                width: 100% !important;
                max-width: 100% !important;
            }
            
            .rule-actions {
                justify-content: space-between;
                width: 100%;
            }
            
            .toggle-rule, .delete-rule, .edit-rule {
                flex: 1;
                text-align: center;
                min-width: unset;
                font-size: 13px;
            }
            
            .rule-item-content div {
                font-size: 13px;
            }
            
            .action-buttons {
                flex-direction: column;
                gap: 10px;
            }
            
            .action-buttons button {
                width: 100%;
            }
            
            .file-drop-area {
                padding: 15px;
            }
            
            .import-export-tab {
                padding: 10px;
                font-size: 13px;
            }
            
            .tab {
                padding: 8px 12px;
                font-size: 14px;
            }
            
            #check-regex, #clear-inputs {
                padding: 8px;
                min-width: 45px;
            }
            
            /* 帮助文本更小一些 */
            .tab-content[data-tab="help"] {
                font-size: 12px;
                line-height: 1.4;
            }
            
            .tab-content[data-tab="help"] ul {
                padding-left: 15px;
            }
        }
        
        /* 按钮样式优化 */
        #check-regex {
            background-color: #4caf50;
            color: white;
            border-color: #43a047;
        }
        
        #check-regex:hover {
            background-color: #43a047;
        }
        
        #clear-inputs {
            background-color: #ff9800;
            color: white;
            border-color: #f57c00;
        }
        
        #clear-inputs:hover {
            background-color: #f57c00;
        }
        
        #close-panel {
            background-color: #f44336;
            color: white;
            border-color: #e53935;
        }
        
        #close-panel:hover {
            background-color: #e53935;
        }
        
        /* 确保结果区域正确显示 */
        #regex-result {
            margin: 5px 0;
            padding: 4px;
            font-size: 12px;
            border-radius: 4px;
            white-space: pre-line;
            line-height: 1.3;
        }
    `);

    // 重定向规则存储
    let rules = GM_getValue('redirect_rules', []);

    // 创建UI
    function createUI() {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'overlay';
        document.body.appendChild(overlay);
        
        const container = document.createElement('div');
        container.id = 'redirector-container';
        container.innerHTML = `
            <div id="redirector-header">
                <h2>URL重定向器</h2>
                <div class="header-actions">
                    <button id="import-export-button">导入/导出</button>
                    <button id="close-panel" title="关闭面板">关闭</button>
                </div>
            </div>
            
            <div class="tabs">
                <div class="tab active" data-tab="add-rule">添加规则</div>
                <div class="tab" data-tab="rule-list">规则列表(${rules.length})</div>
                <div class="tab" data-tab="help">帮助</div>
            </div>
            
            <div class="tab-content active" data-tab="add-rule">
                <div class="section-title">添加重定向规则</div>
                <div class="input-group">
                    <div class="input-row">
                        <select id="rule-type">
                            <option value="regex">正则</option>
                            <option value="pattern">URL模式</option>
                            <option value="wildcard">通配符</option>
                        </select>
                        <input type="text" id="source-url" placeholder="源URL模式">
                        <button id="check-regex" title="检查正则表达式">检查</button>
                    </div>
                    <div id="regex-result" style="margin: 5px 0; font-size: 12px; color: #666;"></div>
                    <div class="input-row">
                        <span class="arrow">→</span>
                        <input type="text" id="target-url" placeholder="目标URL">
                        <div style="display: flex; gap: 5px;">
                            <button id="add-rule">添加</button>
                            <button id="clear-inputs" title="清除输入框">清除</button>
                        </div>
                    </div>
                </div>
                
                <div class="section-title">测试URL</div>
                <div class="input-group">
                    <input type="text" id="test-url" placeholder="输入URL进行测试">
                    <div id="test-result" style="margin-top: 5px; font-size: 12px;"></div>
                </div>
            </div>
            
            <div class="tab-content" data-tab="rule-list">
                <div class="redirector-rules" id="rules-container"></div>
                <div class="action-buttons">
                    <button id="clear-all-rules">清空所有规则</button>
                </div>
            </div>
            
            <div class="tab-content" data-tab="help">
                <div style="font-size: 13px; line-height: 1.5;">
                    <p><strong>规则类型说明:</strong></p>
                    <ul>
                        <li><strong>正则:</strong> 使用JavaScript正则表达式匹配URL</li>
                        <li><strong>URL模式:</strong> 使用URL Pattern API进行匹配，支持捕获组</li>
                        <li><strong>通配符:</strong> 使用*作为通配符匹配URL任意部分</li>
                    </ul>
                    
                    <p><strong>通配符使用指南:</strong></p>
                    <ul>
                        <li>通配符模式使用<code>*</code>匹配任意数量的字符</li>
                        <li>通配符匹配是精确匹配，整个URL必须符合模式</li>
                        <li>例如: <code>https://www.zhihu.com/question/*</code> 匹配所有知乎问题页</li>
                        <li>注意: 通配符不支持捕获参数，如需捕获请使用正则模式</li>
                    </ul>
                    
                    <p><strong>示例:</strong></p>
                    <p>1. 使用通配符将百度跳转到必应:</p>
                    <ul>
                        <li>类型: 通配符</li>
                        <li>源URL: https://www.baidu.com*</li>
                        <li>目标URL: https://cn.bing.com</li>
                    </ul>
                    <p>2. 使用正则将百度搜索跳转到必应搜索:</p>
                    <ul>
                        <li>类型: 正则</li>
                        <li>源URL: https://www.baidu.com/s\\?wd=(.*)</li>
                        <li>目标URL: https://cn.bing.com/search?q=$1</li>
                        <li>说明: 将百度搜索的内容带入必应搜索</li>
                    </ul>
                    <p>3. 将所有Google搜索重定向到DuckDuckGo:</p>
                    <ul>
                        <li>类型: 正则</li>
                        <li>源URL: https://www.google.com/search\\?q=(.*?)&.*</li>
                        <li>目标URL: https://duckduckgo.com/?q=$1</li>
                    </ul>
                    <p>4. 重定向Greasyfork到镜像站:</p>
                    <ul>
                        <li>类型: 正则</li>
                        <li>源URL: ^https?://(www\\.)?greasyfork\\.org/(.*)</li>
                        <li>目标URL: https://greasyfork.dpdns.org/zh-CN/$2</li>
                    </ul>
                    <p>5. 使用通配符保留百度参数:</p>
                    <ul>
                        <li>类型: 通配符</li>
                        <li>源URL: https://www.baidu.com/s*</li>
                        <li>目标URL: https://cn.bing.com/search</li>
                        <li>说明: 当访问百度搜索时会跳转到必应搜索页，但不保留搜索词</li>
                    </ul>
                    <p>6. 使用通配符重定向知乎问题页:</p>
                    <ul>
                        <li>类型: 通配符</li>
                        <li>源URL: https://www.zhihu.com/question/*</li>
                        <li>目标URL: https://web.archive.org/web/*/https://www.zhihu.com/question/$1</li>
                        <li>说明: 将知乎问题页重定向到Web Archive存档页面</li>
                    </ul>
                    <p>7. 重定向特定网站所有二级域名:</p>
                    <ul>
                        <li>类型: 通配符</li>
                        <li>源URL: https://*.example.com/*</li>
                        <li>目标URL: https://example.com</li>
                        <li>说明: 将example.com的所有子域名重定向到主域名</li>
                    </ul>
                </div>
            </div>
            
            <div class="import-export-container" id="import-export-container">
                <div class="section-title">导入/导出规则</div>
                
                <div class="import-export-tabs">
                    <div class="import-export-tab active" data-tab="text">文本格式</div>
                    <div class="import-export-tab" data-tab="file">文件格式</div>
                </div>
                
                <div class="import-export-content active" data-tab="text">
                    <textarea id="import-export-content" placeholder="粘贴JSON格式的规则数据进行导入，或复制此处内容进行导出"></textarea>
                    <div class="action-buttons">
                        <button id="import-rules-text">导入文本</button>
                        <button id="export-rules-text">导出文本</button>
                    </div>
                </div>
                
                <div class="import-export-content" data-tab="file">
                    <div class="file-import">
                        <div class="file-drop-area" id="file-drop-area">
                            <span class="file-msg">拖放JSON文件到此处或</span>
                            <label class="file-input-btn">
                                选择文件
                                <input type="file" id="file-input" accept=".json" style="display: none;">
                            </label>
                        </div>
                        <div id="file-name" class="file-name"></div>
                    </div>
                    <div class="action-buttons">
                        <button id="import-rules-file" disabled>导入文件</button>
                        <button id="export-rules-file">导出到文件</button>
                    </div>
                </div>
                
                <button id="close-import-export" style="width: 100%; margin-top: 15px;">关闭</button>
            </div>
        `;
        
        document.body.appendChild(container);
        
        // 事件监听
        document.getElementById('import-export-button').addEventListener('click', toggleImportExport);
        document.getElementById('close-panel').addEventListener('click', hidePanel);
        document.getElementById('add-rule').addEventListener('click', addRule);
        document.getElementById('test-url').addEventListener('input', testUrlChange);
        document.getElementById('clear-all-rules').addEventListener('click', clearAllRules);
        document.getElementById('import-rules-text').addEventListener('click', importRulesText);
        document.getElementById('export-rules-text').addEventListener('click', exportRulesText);
        document.getElementById('import-rules-file').addEventListener('click', importRulesFile);
        document.getElementById('export-rules-file').addEventListener('click', exportRulesFile);
        document.getElementById('close-import-export').addEventListener('click', toggleImportExport);
        
        // 添加正则表达式检查事件
        document.getElementById('check-regex').addEventListener('click', checkRegex);
        
        // 添加清除输入框事件
        document.getElementById('clear-inputs').addEventListener('click', clearInputs);
        
        // 源URL变化时触发正则检查
        document.getElementById('source-url').addEventListener('input', function() {
            const ruleType = document.getElementById('rule-type').value;
            if (ruleType === 'regex') {
                // 输入停止后延迟检查，避免频繁验证
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    checkRegex();
                }, 500);
            }
        });
        
        // 测试URL变化时也触发正则检查
        document.getElementById('test-url').addEventListener('input', function() {
            const ruleType = document.getElementById('rule-type').value;
            if (ruleType === 'regex') {
                // 输入停止后延迟检查，避免频繁验证
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    checkRegex();
                }, 500);
            }
        });
        
        // 目标URL变化时也触发正则检查
        document.getElementById('target-url').addEventListener('input', function() {
            const ruleType = document.getElementById('rule-type').value;
            if (ruleType === 'regex' && document.getElementById('test-url').value.trim()) {
                // 输入停止后延迟检查，避免频繁验证
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    checkRegex();
                }, 500);
            }
        });
        
        // 规则类型变更时自动检查
        document.getElementById('rule-type').addEventListener('change', function() {
            const regexResult = document.getElementById('regex-result');
            const checkButton = document.getElementById('check-regex');
            
            if (this.value === 'regex') {
                checkButton.style.display = 'inline-block';
                checkRegex();
            } else {
                checkButton.style.display = 'none';
                regexResult.textContent = '';
            }
        });
        
        // 初始设置检查按钮显示状态
        const initialRuleType = document.getElementById('rule-type').value;
        document.getElementById('check-regex').style.display = initialRuleType === 'regex' ? 'inline-block' : 'none';
        
        // 文件导入相关事件
        const fileInput = document.getElementById('file-input');
        const fileDropArea = document.getElementById('file-drop-area');
        const fileName = document.getElementById('file-name');
        const importFileButton = document.getElementById('import-rules-file');
        
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                fileName.textContent = this.files[0].name;
                importFileButton.disabled = false;
            } else {
                fileName.textContent = '';
                importFileButton.disabled = true;
            }
        });
        
        fileDropArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('active');
        });
        
        fileDropArea.addEventListener('dragleave', function() {
            this.classList.remove('active');
        });
        
        fileDropArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('active');
            
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                fileName.textContent = e.dataTransfer.files[0].name;
                importFileButton.disabled = false;
            }
        });
        
        fileDropArea.addEventListener('click', function() {
            fileInput.click();
        });
        
        // 导入导出标签切换
        document.querySelectorAll('.import-export-tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.import-export-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.import-export-content').forEach(c => c.classList.remove('active'));
                
                tab.classList.add('active');
                document.querySelector(`.import-export-content[data-tab="${tab.dataset.tab}"]`).classList.add('active');
            });
        });
        
        // 标签切换
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
                
                tab.classList.add('active');
                document.querySelector(`.tab-content[data-tab="${tab.dataset.tab}"]`).classList.add('active');
                
                // 如果切换到规则列表标签，更新标签显示的规则数量
                if (tab.dataset.tab === 'rule-list') {
                    document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
                }
            });
        });
        
        // 点击遮罩层关闭面板
        overlay.addEventListener('click', () => {
            hidePanel();
        });
        
        // 渲染规则列表
        renderRules();
    }

    // 切换主题
    function toggleTheme() {
        // 主题切换逻辑
    }

    // 添加规则
    function addRule() {
        const ruleType = document.getElementById('rule-type').value;
        const sourceUrl = document.getElementById('source-url').value.trim();
        const targetUrl = document.getElementById('target-url').value.trim();
        
        if (!sourceUrl || !targetUrl) {
            alert('请输入源URL和目标URL');
            return;
        }
        
        // 如果是正则表达式类型，先验证正则表达式
        if (ruleType === 'regex') {
            try {
                new RegExp(sourceUrl);
            } catch (error) {
                if (!confirm(`正则表达式有错误: ${error.message}\n是否仍要添加？`)) {
                    return;
                }
            }
        }
        
        const rule = {
            type: ruleType,
            source: sourceUrl,
            target: targetUrl,
            enabled: true
        };
        
        rules.push(rule);
        GM_setValue('redirect_rules', rules);
        
        // 清空输入框
        document.getElementById('source-url').value = '';
        document.getElementById('target-url').value = '';
        
        // 更新规则标签数量
        document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
        
        // 重新渲染规则列表
        renderRules();
        
        // 提示添加成功
        const testResult = document.getElementById('test-result');
        testResult.textContent = '规则添加成功！';
        testResult.style.color = 'green';
        setTimeout(() => {
            testResult.textContent = '';
        }, 2000);
        
        // 清除编辑状态样式
        document.getElementById('add-rule').textContent = '添加';
        
        // 将第一个section-title标题改回原样
        const sectionTitles = document.querySelectorAll('.section-title');
        if (sectionTitles.length > 0) {
            sectionTitles[0].textContent = '添加重定向规则';
        }
    }

    // 删除规则
    function deleteRule(index) {
        if (confirm('确定要删除这条规则吗？')) {
            rules.splice(index, 1);
            GM_setValue('redirect_rules', rules);
            
            // 更新规则标签数量
            document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
            
            renderRules();
        }
    }

    // 清空所有规则
    function clearAllRules() {
        if (rules.length === 0) {
            alert('没有规则可清空');
            return;
        }
        
        if (confirm('确定要清空所有规则吗？此操作不可恢复！')) {
            rules = [];
            GM_setValue('redirect_rules', rules);
            
            // 更新规则标签数量
            document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
            
            renderRules();
        }
    }

    // 切换规则启用状态
    function toggleRule(index) {
        rules[index].enabled = !rules[index].enabled;
        GM_setValue('redirect_rules', rules);
        renderRules();
    }

    // 切换导入导出面板
    function toggleImportExport() {
        const importExportContainer = document.getElementById('import-export-container');
        
        if (importExportContainer.style.display === 'none' || importExportContainer.style.display === '') {
            importExportContainer.style.display = 'block';
        } else {
            importExportContainer.style.display = 'none';
        }
    }

    // 导入规则
    function importRulesText() {
        const importContent = document.getElementById('import-export-content').value.trim();
        
        if (!importContent) {
            alert('请输入要导入的规则JSON数据');
            return;
        }
        
        try {
            const importedRules = JSON.parse(importContent);
            
            if (!Array.isArray(importedRules)) {
                alert('导入数据格式错误，必须是规则数组');
                return;
            }
            
            // 验证规则格式
            let isValid = true;
            importedRules.forEach((rule, index) => {
                // 转换from/to/mode字段
                // 如果规则使用from/to字段（兼容其他脚本的格式），则转换为source/target
                if (rule.from && !rule.source) {
                    rule.source = rule.from;
                    delete rule.from;
                }
                
                if (rule.to && !rule.target) {
                    rule.target = rule.to;
                    delete rule.to;
                }
                
                // 如果规则使用mode字段，则转换为type
                if (rule.mode && !rule.type) {
                    rule.type = rule.mode;
                    delete rule.mode;
                }
                
                // 检查是否有基本的源URL和目标URL字段
                if (!rule.source || !rule.target) {
                    alert(`规则 #${index + 1} 缺少必要字段`);
                    isValid = false;
                    return;
                }
                
                // 确保type字段正确
                if (!rule.type) {
                    rule.type = 'regex'; // 默认使用正则表达式
                }
                
                // 确保enabled字段存在
                if (rule.enabled === undefined) {
                    rule.enabled = true;
                }
            });
            
            if (!isValid) return;
            
            // 询问用户是追加还是替换
            const action = confirm('是否替换当前所有规则？\n点击"确定"替换所有规则\n点击"取消"追加到现有规则');
            
            if (action) {
                // 替换
                rules = importedRules;
            } else {
                // 追加
                rules = rules.concat(importedRules);
            }
            
            GM_setValue('redirect_rules', rules);
            
            // 更新规则标签数量
            document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
            
            renderRules();
            alert(`成功导入 ${importedRules.length} 条规则！`);
            
            // 清空导入框
            document.getElementById('import-export-content').value = '';
            
            // 自动切换到规则列表标签
            document.querySelector('.tab[data-tab="rule-list"]').click();
            
        } catch (error) {
            alert('导入失败，请检查JSON格式是否正确: ' + error.message);
        }
    }

    // 导出规则
    function exportRulesText() {
        if (rules.length === 0) {
            alert('没有规则可导出');
            return;
        }
        
        const exportContent = JSON.stringify(rules, null, 2);
        document.getElementById('import-export-content').value = exportContent;
        
        // 选中文本方便复制
        document.getElementById('import-export-content').select();
    }

    // 导入规则
    function importRulesFile() {
        const fileInput = document.getElementById('file-input');
        const fileDropArea = document.getElementById('file-drop-area');
        const fileName = document.getElementById('file-name');
        
        if (fileInput.files.length === 0) {
            alert('请选择要导入的JSON文件');
            return;
        }
        
        const file = fileInput.files[0];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            const importedRules = JSON.parse(e.target.result);
            
            if (!Array.isArray(importedRules)) {
                alert('导入数据格式错误，必须是规则数组');
                return;
            }
            
            // 验证规则格式
            let isValid = true;
            importedRules.forEach((rule, index) => {
                // 转换from/to/mode字段
                // 如果规则使用from/to字段（兼容其他脚本的格式），则转换为source/target
                if (rule.from && !rule.source) {
                    rule.source = rule.from;
                    delete rule.from;
                }
                
                if (rule.to && !rule.target) {
                    rule.target = rule.to;
                    delete rule.to;
                }
                
                // 如果规则使用mode字段，则转换为type
                if (rule.mode && !rule.type) {
                    rule.type = rule.mode;
                    delete rule.mode;
                }
                
                // 检查是否有基本的源URL和目标URL字段
                if (!rule.source || !rule.target) {
                    alert(`规则 #${index + 1} 缺少必要字段`);
                    isValid = false;
                    return;
                }
                
                // 确保type字段正确
                if (!rule.type) {
                    rule.type = 'regex'; // 默认使用正则表达式
                }
                
                // 确保enabled字段存在
                if (rule.enabled === undefined) {
                    rule.enabled = true;
                }
            });
            
            if (!isValid) return;
            
            // 询问用户是追加还是替换
            const action = confirm('是否替换当前所有规则？\n点击"确定"替换所有规则\n点击"取消"追加到现有规则');
            
            if (action) {
                // 替换
                rules = importedRules;
            } else {
                // 追加
                rules = rules.concat(importedRules);
            }
            
            GM_setValue('redirect_rules', rules);
            
            // 更新规则标签数量
            document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
            
            renderRules();
            alert(`成功导入 ${importedRules.length} 条规则！`);
            
            // 清空导入框
            fileInput.value = '';
            fileName.textContent = '';
            
            // 自动切换到规则列表标签
            document.querySelector('.tab[data-tab="rule-list"]').click();
            
        };
        
        reader.onerror = function(e) {
            alert('导入失败，请检查文件格式是否正确: ' + e.target.error.message);
        };
        
        reader.readAsText(file);
    }

    // 导出规则到文件
    function exportRulesFile() {
        if (rules.length === 0) {
            alert('没有规则可导出');
            return;
        }
        
        // 创建数据
        const rulesJson = JSON.stringify(rules, null, 2);
        const blob = new Blob([rulesJson], {type: 'application/json'});
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'url_redirector_rules.json';
        
        // 触发下载
        document.body.appendChild(a);
        a.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 0);
    }

    // 渲染规则列表
    function renderRules() {
        const rulesContainer = document.getElementById('rules-container');
        rulesContainer.innerHTML = '';
        
        if (rules.length === 0) {
            rulesContainer.innerHTML = '<div style="padding: 10px; text-align: center; color: #888;">暂无规则</div>';
            return;
        }
        
        rules.forEach((rule, index) => {
            const ruleItem = document.createElement('div');
            ruleItem.className = 'rule-item';
            
            // 根据规则类型显示中文名称
            let typeText = '';
            switch (rule.type) {
                case 'regex':
                    typeText = '正则';
                    break;
                case 'pattern':
                    typeText = 'URL模式';
                    break;
                case 'wildcard':
                    typeText = '通配符';
                    break;
                default:
                    typeText = rule.type;
            }
            
            // 截取过长的URL显示，移动端显示更短
            const isMobile = window.innerWidth <= 600;
            const maxSourceLength = isMobile ? 30 : 60;
            const maxTargetLength = isMobile ? 30 : 60;
            
            let displaySource = rule.source;
            let displayTarget = rule.target;
            
            if (displaySource.length > maxSourceLength) {
                displaySource = displaySource.substring(0, maxSourceLength) + '...';
            }
            
            if (displayTarget.length > maxTargetLength) {
                displayTarget = displayTarget.substring(0, maxTargetLength) + '...';
            }
            
            ruleItem.innerHTML = `
                <div class="rule-item-content">
                    <div><strong>${typeText}:</strong> <span title="${rule.source}">${displaySource}</span></div>
                    <div>→ <span title="${rule.target}">${displayTarget}</span></div>
                    <div style="font-size: 12px; color: #888; margin-top: 4px;">${rule.enabled ? '<span style="color: green;">已启用</span>' : '<span style="color: red;">已禁用</span>'}</div>
                </div>
                <div class="rule-actions">
                    <button class="edit-rule" data-index="${index}" title="编辑规则">编辑</button>
                    <button class="toggle-rule" data-index="${index}" data-enabled="${rule.enabled}" title="${rule.enabled ? '点击禁用' : '点击启用'}">${rule.enabled ? '禁用' : '启用'}</button>
                    <button class="delete-rule" data-index="${index}" title="删除规则">删除</button>
                </div>
            `;
            
            rulesContainer.appendChild(ruleItem);
        });
        
        // 添加事件监听
        document.querySelectorAll('.toggle-rule').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.target.getAttribute('data-index'));
                toggleRule(index);
            });
        });
        
        document.querySelectorAll('.delete-rule').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.target.getAttribute('data-index'));
                deleteRule(index);
            });
        });
        
        document.querySelectorAll('.edit-rule').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.target.getAttribute('data-index'));
                editRule(index);
            });
        });
    }

    // 编辑规则
    function editRule(index) {
        const rule = rules[index];
        
        // 切换到添加规则标签
        document.querySelector('.tab[data-tab="add-rule"]').click();
        
        // 填充表单
        document.getElementById('rule-type').value = rule.type;
        document.getElementById('source-url').value = rule.source;
        document.getElementById('target-url').value = rule.target;
        
        // 移除旧规则
        rules.splice(index, 1);
        GM_setValue('redirect_rules', rules);
        
        // 更新UI
        renderRules();
        
        // 更新规则数量显示
        document.querySelector('.tab[data-tab="rule-list"]').textContent = `规则列表(${rules.length})`;
        
        // 提示用户
        const testResult = document.getElementById('test-result');
        testResult.textContent = '正在编辑规则，修改后点击保存按钮';
        testResult.style.color = '#4a90e2';
        
        // 更改按钮和标题文本以指示编辑模式
        document.getElementById('add-rule').textContent = '保存';
        
        // 将第一个section-title标题改为编辑模式
        const sectionTitles = document.querySelectorAll('.section-title');
        if (sectionTitles.length > 0) {
            sectionTitles[0].textContent = '编辑重定向规则';
        }
    }

    // 测试URL变更
    function testUrlChange(e) {
        const testUrl = e.target.value.trim();
        const testResult = document.getElementById('test-result');
        
        if (!testUrl) {
            testResult.textContent = '';
            e.target.style.color = '';
            return;
        }
        
        for (const rule of rules) {
            if (!rule.enabled) continue;
            
            let matches = false;
            let targetUrl = rule.target;
            
            if (rule.type === 'regex') {
                try {
                    const regex = new RegExp(rule.source);
                    matches = regex.test(testUrl);
                    if (matches) {
                        targetUrl = testUrl.replace(regex, rule.target);
                    }
                } catch (error) {
                    console.error('无效的正则表达式:', error);
                }
            } else if (rule.type === 'wildcard') {
                // 简单的通配符实现
                const pattern = rule.source.replace(/\*/g, '.*');
                const regex = new RegExp(`^${pattern}$`);
                matches = regex.test(testUrl);
            } else if (rule.type === 'pattern') {
                // URL Pattern 实现
                try {
                    const urlPattern = new URLPattern(rule.source);
                    matches = urlPattern.test(testUrl);
                    if (matches) {
                        // 提取参数用于替换
                        const components = urlPattern.exec(testUrl);
                        targetUrl = rule.target;
                        
                        // 替换 :group 格式的变量
                        if (components) {
                            for (const [key, value] of Object.entries(components.pathname.groups)) {
                                if (value) targetUrl = targetUrl.replace(new RegExp(`:${key}`, 'g'), value);
                            }
                            
                            // 替换 $1, $2 等格式的变量
                            Object.values(components.pathname.groups).forEach((value, index) => {
                                if (value) targetUrl = targetUrl.replace(new RegExp(`\\$${index + 1}`, 'g'), value);
                            });
                        }
                    }
                } catch (error) {
                    console.error('无效的URL Pattern:', error);
                }
            }
            
            if (matches) {
                e.target.style.color = 'green';
                testResult.textContent = `匹配成功! 将重定向到: ${targetUrl}`;
                testResult.style.color = 'green';
                return;
            }
        }
        
        e.target.style.color = '';
        testResult.textContent = '没有匹配的规则';
        testResult.style.color = '#888';
    }

    // 检查URL并重定向
    function checkAndRedirect() {
        const currentUrl = window.location.href;
        
        for (const rule of rules) {
            if (!rule.enabled) continue;
            
            let matches = false;
            let targetUrl = rule.target;
            
            if (rule.type === 'regex') {
                try {
                    const regex = new RegExp(rule.source);
                    matches = regex.test(currentUrl);
                    if (matches) {
                        targetUrl = currentUrl.replace(regex, rule.target);
                    }
                } catch (error) {
                    console.error('无效的正则表达式:', error);
                }
            } else if (rule.type === 'wildcard') {
                const pattern = rule.source.replace(/\*/g, '.*');
                const regex = new RegExp(`^${pattern}$`);
                matches = regex.test(currentUrl);
            } else if (rule.type === 'pattern') {
                try {
                    // URL Pattern API可能在一些浏览器中不可用
                    if (typeof URLPattern === 'undefined') {
                        console.error('当前浏览器不支持URL Pattern API');
                        continue;
                    }
                    
                    const urlPattern = new URLPattern(rule.source);
                    matches = urlPattern.test(currentUrl);
                    if (matches) {
                        // 提取参数用于替换
                        const components = urlPattern.exec(currentUrl);
                        targetUrl = rule.target;
                        
                        // 替换目标URL中的变量
                        if (components) {
                            // 替换 :group 格式的变量
                            for (const [key, value] of Object.entries(components.pathname.groups)) {
                                if (value) targetUrl = targetUrl.replace(new RegExp(`:${key}`, 'g'), value);
                            }
                            
                            // 替换 $1, $2 等格式的变量
                            Object.values(components.pathname.groups).forEach((value, index) => {
                                if (value) targetUrl = targetUrl.replace(new RegExp(`\\$${index + 1}`, 'g'), value);
                            });
                        }
                    }
                } catch (error) {
                    console.error('无效的URL Pattern:', error);
                }
            }
            
            if (matches && currentUrl !== targetUrl) {
                // 使用replace而不是href以避免历史记录
                console.log(`URL重定向器: 将 ${currentUrl} 重定向到 ${targetUrl}`);
                
                // 中断当前页面加载并立即重定向
                if (document.readyState !== 'complete') {
                    document.documentElement.innerHTML = ''; // 清空页面内容
                }
                
                window.location.replace(targetUrl);
                return;
            }
        }
    }

    // 显示面板
    function showPanel() {
        const container = document.getElementById('redirector-container');
        const overlay = document.querySelector('.overlay');
        container.style.display = 'block';
        overlay.style.display = 'block';
    }

    // 隐藏面板
    function hidePanel() {
        const container = document.getElementById('redirector-container');
        const overlay = document.querySelector('.overlay');
        container.style.display = 'none';
        overlay.style.display = 'none';
        
        // 隐藏导入导出面板
        document.getElementById('import-export-container').style.display = 'none';
    }

    // 注册菜单命令
    GM_registerMenuCommand('URL重定向设置', showPanel);

    // 初始化 - 在文档开始时立即检查重定向
    checkAndRedirect();
    
    // 同时也在页面加载完成后创建UI
    window.addEventListener('load', createUI);

    // 检查正则表达式
    function checkRegex() {
        const sourceUrl = document.getElementById('source-url').value.trim();
        const regexResult = document.getElementById('regex-result');
        const testUrl = document.getElementById('test-url').value.trim();
        
        if (!sourceUrl) {
            regexResult.textContent = '';
            return;
        }
        
        try {
            const regex = new RegExp(sourceUrl);
            regexResult.textContent = '✓ 正则表达式有效';
            regexResult.style.color = 'green';
            
            // 尝试提供一些正则表达式分析
            const analysis = [];
            
            // 检查是否有捕获组
            const groupCount = (sourceUrl.match(/\((?!\?)/g) || []).length;
            if (groupCount > 0) {
                analysis.push(`包含 ${groupCount} 个捕获组`);
            }
            
            // 检查常见模式
            if (sourceUrl.includes('^')) analysis.push('匹配开头');
            if (sourceUrl.includes('$')) analysis.push('匹配结尾');
            if (sourceUrl.includes('.*')) analysis.push('包含通配符');
            if (sourceUrl.includes('\\d')) analysis.push('匹配数字');
            if (sourceUrl.includes('[')) analysis.push('包含字符类');
            
            if (analysis.length > 0) {
                regexResult.textContent += ` (${analysis.join(', ')})`;
            }
            
            // 检查是否符合URL格式
            if (!sourceUrl.includes('http') && !sourceUrl.includes('^http')) {
                regexResult.textContent += '\n提示: 您的正则可能缺少http(s)://前缀';
            }
            
            // 测试是否匹配当前测试URL
            if (testUrl) {
                const matches = regex.test(testUrl);
                if (matches) {
                    const replaced = testUrl.replace(regex, document.getElementById('target-url').value.trim());
                    regexResult.textContent += `\n测试URL匹配成功! 替换结果: ${replaced}`;
                } else {
                    regexResult.textContent += '\n测试URL不匹配此正则表达式';
                }
            }
            
            return true;
        } catch (error) {
            regexResult.textContent = `✗ 正则表达式错误: ${error.message}`;
            regexResult.style.color = 'red';
            return false;
        }
    }

    // 清除输入框
    function clearInputs() {
        // 清除输入值
        document.getElementById('source-url').value = '';
        document.getElementById('target-url').value = '';
        document.getElementById('test-url').value = '';
        document.getElementById('regex-result').textContent = '';
        document.getElementById('test-result').textContent = '';
        
        // 清除浏览器自动填充历史记录
        // 通过临时创建新输入框替换原有输入框的方式清除历史记录
        const sourceUrlInput = document.getElementById('source-url');
        const targetUrlInput = document.getElementById('target-url');
        const testUrlInput = document.getElementById('test-url');
        
        // 创建新输入框并复制原有输入框的属性
        function replaceInput(oldInput) {
            const newInput = document.createElement('input');
            newInput.type = 'text';
            newInput.id = oldInput.id;
            newInput.className = oldInput.className;
            newInput.placeholder = oldInput.placeholder;
            
            // 复制事件监听器
            if (oldInput.id === 'source-url') {
                newInput.addEventListener('input', function() {
                    const ruleType = document.getElementById('rule-type').value;
                    if (ruleType === 'regex') {
                        clearTimeout(this.timer);
                        this.timer = setTimeout(() => {
                            checkRegex();
                        }, 500);
                    }
                });
            } else if (oldInput.id === 'test-url') {
                newInput.addEventListener('input', testUrlChange);
            } else if (oldInput.id === 'target-url') {
                newInput.addEventListener('input', function() {
                    const ruleType = document.getElementById('rule-type').value;
                    if (ruleType === 'regex' && document.getElementById('test-url').value.trim()) {
                        clearTimeout(this.timer);
                        this.timer = setTimeout(() => {
                            checkRegex();
                        }, 500);
                    }
                });
            }
            
            // 替换输入框
            oldInput.parentNode.replaceChild(newInput, oldInput);
        }
        
        // 替换所有输入框
        replaceInput(sourceUrlInput);
        replaceInput(targetUrlInput);
        replaceInput(testUrlInput);
        
        // 恢复添加按钮和标题文本（如果处于编辑模式）
        document.getElementById('add-rule').textContent = '添加';
        
        // 恢复第一个section-title标题
        const sectionTitles = document.querySelectorAll('.section-title');
        if (sectionTitles.length > 0) {
            sectionTitles[0].textContent = '添加重定向规则';
        }
        
        // 提示用户
        setTimeout(() => {
            const testResult = document.getElementById('test-result');
            testResult.textContent = '已清除所有输入和历史记录';
            testResult.style.color = '#4a90e2';
            
            // 2秒后清除提示
            setTimeout(() => {
                testResult.textContent = '';
            }, 2000);
        }, 100);
    }
})(); 